<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>07_封装getClassName</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            margin:10px auto;
            background-color: orange;
        }
    </style>
    <script>
        window.onload = function () {
            function getClass(classname) {
                if (document.getElementsByClassName){
                    return document.getElementsByClassName(classname);
                }

                var attr = [];
                var elements = document.getElementsByTagName("*");
                for (var i = 0; i < elements.length; i++) {
                    var obj = elements[i];
                    var objCN = obj.className;
                    //var pattern = new RegExp(classname,"g");
                    var pattern = new RegExp("(^| )("+classname+")( |$)","g");
                    if(pattern.test(objCN)){
                        attr.push(obj);
                    }
                }
                return attr;
            }
            var attrDemo = getClass("demo");

            for (var i = 0; i < attrDemo.length; i++) {
                var obj = attrDemo[i];
                obj.style.backgroundColor = "#ff705e";
            }
        }
    </script>
</head>
<body>
<div class="test demo one"></div>
<div></div>
<div></div>
<div class="demo one"></div>
<div class="demo one"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div class="demo2"></div>
</body>
</html>